package org.linlinjava.litemall.db.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.linlinjava.litemall.db.dao.CommentMapper;
import org.linlinjava.litemall.db.models.Comment;
import org.linlinjava.litemall.db.service.CommentService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment>
        implements CommentService {

    @Override
    public IPage<Comment> queryGoodsByGid(Long id, int offset, int limit) {
        Page<Comment> page = new Page<>(offset, limit);
        return this.baseMapper.selectPage(page, new LambdaQueryWrapper<Comment>()
                .eq(Comment::getValueId, id)
                .eq(Comment::getType, 0));
    }

    @Override
    public IPage<Comment> query(Byte type, Integer valueId, Integer showType, Integer offset, Integer limit) {
        Page<Comment> page = new Page<>(offset, limit);
        QueryWrapper<Comment> query = new QueryWrapper<>();
        query.orderByDesc("add_time");

        query.eq("value_id", valueId).eq("type", type);
        if (showType == 1) {
            query.eq("has_picture", true);
        }
        return this.baseMapper.selectPage(page, query);
    }

    @Override
    public int count(Byte type, Integer valueId, Integer showType) {
        QueryWrapper<Comment> query = new QueryWrapper<>();
        if (showType == 0) {
            query.eq("value_id", valueId).eq("type", type);
        } else if (showType == 1) {
            query.eq("value_id", valueId).eq("type", type).eq("has_picture", true);
        } else {
            throw new RuntimeException("showType不支持");
        }
        return this.baseMapper.selectCount(query);
    }

    @Override
    public IPage<Comment> querySelective(String userId, String valueId, Integer pageNo, Integer pageSize) {
        Page<Comment> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Comment> query = new QueryWrapper<>();
        query.ne("type", 2);
        // type=2 是订单商品回复，这里过滤
        query.eq(!StringUtils.isEmpty(userId), "user_id", userId);
        if (!StringUtils.isEmpty(valueId)) {
            query.eq("value_id", valueId);
            query.eq("type", 0);
        }
        return this.baseMapper.selectPage(page, query);
    }
}
